package com.example.peng.myokhttpfinal;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.TextView;

import cn.finalteam.okhttpfinal.HttpRequest;

/**
 * Created by EricYuan on 2017/3/9.
 */

public class LoadingDialog extends Dialog {
    private Context context;
    private ImageView dialogLoading_img;
    private TextView loadingMsg;
    private AnimationDrawable animationDrawable = null;
    private String[] requestUrl;


    public LoadingDialog(Context context) {
        super(context, R.style.onLoadingDialog);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_loading);
        dialogLoading_img = (ImageView) findViewById(R.id.dialogLoading_img);
        loadingMsg = (TextView) findViewById(R.id.loadingMsg);
        animationDrawable = (AnimationDrawable) dialogLoading_img.getDrawable();
    }

    public void setLoadingMsg(String msg) {
        if (!StringDela.isNull(msg) && loadingMsg != null)
            loadingMsg.setText(msg);
    }

    public void setOkHttpUrl(String[] requestUrl) {
        this.requestUrl = requestUrl;
    }

    @Override
    public void show() {
        super.show();
        animationDrawable.start();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        animationDrawable.stop();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (isShowing()) {
                cancelRequest();
                dismiss();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void cancelRequest() {
        if (requestUrl == null)
            return;
        if (requestUrl.length == 0)
            return;
        for (int i = 0; i < requestUrl.length; i++) {
            HttpRequest.cancel(requestUrl[i]);
        }
    }
}
